from collections import defaultdict
from 三维投影线段寻找 import get_adjusted_clusters,get_clusters,get_intersect_lines


dxf_file_path = 'f.dxf'

clusters=get_clusters(dxf_file_path)

adjusted_clusters,yz中间面线段集,xy上下面线段集,xz左右面线段集  =get_adjusted_clusters(clusters)
intersect_lines=get_intersect_lines(xz左右面线段集,yz中间面线段集,xy上下面线段集)
intersect_lines1,intersect_lines2,intersect_lines3 = intersect_lines

import networkx as nx
from OCC.Core.BRepBuilderAPI import (
    BRepBuilderAPI_MakePolygon,
    BRepBuilderAPI_MakeFace,
    BRepBuilderAPI_MakeShell,
    BRepBuilderAPI_MakeSolid
)
from OCC.Core.BRep import BRep_Builder
from OCC.Core.TopoDS import TopoDS_Compound, TopoDS_Shell

from OCC.Core.BRepLib import breplib_BuildCurves3d
from OCC.Core.gp import gp_Pnt

def get_closed_subgraphs_in_open_faces(intersect_lines):
    all_polygons = []
    G = nx.Graph()
    G.add_edges_from(intersect_lines)
    cycles = list(nx.cycle_basis(G))
    for cycle in cycles:
        if cycle[0] != cycle[-1]:
            cycle.append(cycle[0])
        all_polygons.append(cycle)
    return all_polygons

def create_face_from_polygon(points):
    make_polygon = BRepBuilderAPI_MakePolygon()
    for pt in points:
        make_polygon.Add(gp_Pnt(*pt))
    make_polygon.Close()
    wire = make_polygon.Wire()
    breplib_BuildCurves3d(wire)
    face = BRepBuilderAPI_MakeFace(wire).Face()
    return face

def create_shell_and_solid(polygons):
    """
    输入：polygons 是所有多边形点集 [[(x, y, z), ...], ...]
    输出：TopoDS_Solid
    """
    builder = BRep_Builder()
    shell = TopoDS_Shell()
    builder.MakeShell(shell)
    for polygon in polygons:
        face = create_face_from_polygon(polygon)
        builder.Add(shell, face)
    solid_builder = BRepBuilderAPI_MakeSolid(shell)
    solid = solid_builder.Solid()
    return solid



# 生成所有多边形
polygons1 = get_closed_subgraphs_in_open_faces(intersect_lines1)
polygons2 = get_closed_subgraphs_in_open_faces(intersect_lines2)
polygons3 = get_closed_subgraphs_in_open_faces(intersect_lines3)
all_polygons = polygons1 + polygons2 + polygons3

# 构建实体
solid = create_shell_and_solid(all_polygons)
# 显示模块
from OCC.Display.SimpleGui import init_display
display, start_display, add_menu, add_function_to_menu = init_display()
display.DisplayShape(solid, update=True)
start_display()
print("finished.")